<?php

namespace App\Service\playlet;
use App\Model\AppletCoupon;
use App\Model\Applet;
use App\Model\AppletCouponPromotionActivity;
use App\Service\CommicService;
use Hyperf\Utils\ApplicationContext;
use App\Common\Response\SystemCode;
use Hyperf\DbConnection\Db;
use App\Service\queue\DyCouponService;
use Hyperf\Di\Annotation\Inject;
class AppletCouponService extends CommicService
{
    const cacheDuration = 60 * 15;

    #[Inject]
    private DyCouponService $dyCouponService;

    public function __construct()
    {
        $container = ApplicationContext::getContainer();
        $this->redisService = $container->get(\Hyperf\Redis\Redis::class);
    }


    const STATUS_ENABLE  = 1;


    public function search(Array $params){

        $keyword     = $params['keyword'] ?? '';
        $pageSize    = $params['pageSize'] ?? 10;
        $page        = $params['page'] ?? 1;

        $query = AppletCoupon::query()
            ->leftJoin('applet','applet.id','=','applet_coupon.applet_id')
            ->select(['applet_coupon.id','applet_coupon.name','applet.name as applet_name','discount_type','applet_coupon.status','receive_begin_time','receive_end_time','stock_number','consume_desc','applet_coupon.created_at','applet_coupon.updated_at']);

        if ($keyword) {
            $query->orWhere([['applet_coupon.name', 'like', '%'.$keyword.'%']]);
        }
        $models = $query->orderBy('id','desc')->paginate($pageSize,['*'],'page',$page);
        return $models;
    }


    public function selectCoupon($appletCouponInfo){
        $selectResult = $this->dyCouponService->selectCoupon($appletCouponInfo);
        return $selectResult;
    }

    public function createOrUpdate(Array $postData,$is_update=false,AppletCoupon $AppletCouponInfo = null){


        //小程序券参数
        $applet_id = $postData['applet_id'];
        $name = $postData['name'];
        $discount_type = $postData['discount_type'] ?? 0;
        $receive_time = $postData['receive_time'];
        $receive_begin_time = $receive_time[0];
        $receive_end_time = $receive_time[1];
        $valid_type = $postData['valid_type']  ?? 0;
        $valid_duration = $postData['valid_duration'];
        $stock_number = $postData['stock_number'] ?? 0;
        $consume_desc = $postData['consume_desc'];
        $receive_desc = $postData['receive_desc'] ?? '';
        $send_desc = $postData['send_desc'] ?? '';

        //查询投放平台是否存在
        $appletData = Applet::query()->where(['id' => $applet_id])->select(['id','app_id'])->first();
        if(empty($appletData)){
            return $this->response(SystemCode::SYSTEM_ERROR, '小程序不存在');
        }

        if (strtotime($receive_begin_time) >= strtotime($receive_end_time)) {
            return $this->response(SystemCode::SYSTEM_ERROR, '券开始时间不能大于结束时间');
        }

        Db::beginTransaction();
        try {

            $model = !empty($AppletCouponInfo)? $AppletCouponInfo : new AppletCoupon();
            $model->name = $name;
            $model->receive_begin_time = $receive_begin_time;
            $model->receive_end_time = $receive_end_time;
            $model->valid_duration = $valid_duration;
            if(!$is_update){
                $model->valid_type = $valid_type;
                $model->applet_id = $applet_id;
                $model->discount_type = $discount_type;
                $model->stock_number = $stock_number;
            }
            $model->consume_desc = $consume_desc;
            $model->receive_desc = $receive_desc;
            $model->send_desc = $send_desc;
            if($model->save()){

                if($is_update){

                    $updateResult = $this->dyCouponService->updateCoupon($model,$appletData->app_id);
                    if($updateResult['err_no'] != 0){
                        Db::rollBack();
                        return $this->response(SystemCode::SYSTEM_ERROR, $updateResult['err_msg']);
                    }

                }else{
                    $createResult = $this->dyCouponService->createCoupon($model,$appletData->app_id);
                    if($createResult['err_no'] != 0){
                        Db::rollBack();
                        return $this->response(SystemCode::SYSTEM_ERROR, $createResult['err_msg']);
                    }
                    $coupon_meta_id = $createResult['data']['coupon_meta_id'];
                    $model->coupon_meta_id = $coupon_meta_id;
                    $model->save();
                }
                Db::commit();
                return $this->response(SystemCode::SYSTEM_SUCCESS);
            }else{
                Db::rollBack();
                return $this->response(SystemCode::SYSTEM_ERROR,'保存错误');
            }

        }catch (\Exception $e){
            Db::rollBack();
            return $this->response(SystemCode::SYSTEM_ERROR,$e->getMessage());
        }

    }
    public function deleteCoupon($appletCouponInfo){
        Db::beginTransaction();
        try {

            $deleteResult = $this->dyCouponService->deleteCoupon($appletCouponInfo);
            if($deleteResult['err_no'] != 0) {
                Db::rollBack();
                return $this->response(SystemCode::SYSTEM_ERROR, $deleteResult['err_msg']);
            }
            $appletCouponInfo->deleted_at = date('Y-m-d H:i:s');
            $appletCouponInfo->save();
            Db::commit();
            return $this->response(SystemCode::SYSTEM_SUCCESS);
        }catch (\Exception $e){
            Db::rollBack();
            return $this->response(SystemCode::SYSTEM_ERROR,$e->getMessage());
        }
    }

    public function updateMetaStock($appletCouponInfo,$params){
        Db::beginTransaction();
        try {

            $add_number = $params['add_number'];
            $stock_number = $appletCouponInfo->stock_number;
            $deleteResult = $this->dyCouponService->updateMetaStock($appletCouponInfo,$add_number);
            if($deleteResult['err_no'] != 0) {
                Db::rollBack();
                return $this->response(SystemCode::SYSTEM_ERROR, $deleteResult['err_msg']);
            }
            $appletCouponInfo->stock_number = $stock_number+$add_number;
            $appletCouponInfo->save();
            Db::commit();
            return $this->response(SystemCode::SYSTEM_SUCCESS);
        }catch (\Exception $e){
            Db::rollBack();
            return $this->response(SystemCode::SYSTEM_ERROR,$e->getMessage());
        }
    }

    public function updateMetaStatus($appletCouponInfo,$params){
        Db::beginTransaction();
        try {

            $coupon_meta_status = $params['status'];
            $deleteResult = $this->dyCouponService->updateMetaStatus($appletCouponInfo,$coupon_meta_status);
            if($deleteResult['err_no'] != 0) {
                Db::rollBack();
                return $this->response(SystemCode::SYSTEM_ERROR, $deleteResult['err_msg']);
            }
            $appletCouponInfo->status = $coupon_meta_status;
            $appletCouponInfo->save();
            Db::commit();
            return $this->response(SystemCode::SYSTEM_SUCCESS);
        }catch (\Exception $e){
            Db::rollBack();
            return $this->response(SystemCode::SYSTEM_ERROR,$e->getMessage());
        }
    }
}